package com.ruoyi.base.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.base.domain.vo.BaseBsBdVo;
import com.ruoyi.base.mapper.BaseBsBdMapper;
import com.ruoyi.base.service.IBaseBsBdService;
import com.ruoyi.cm.domain.CmBsContractInfo;
import com.ruoyi.cm.mapper.CmBsContractInfoMapper;
import com.ruoyi.cm.mapper.CmBsStartAdvanceMapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.BigDecimalUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.domain.SysUserPower;
import com.ruoyi.system.mapper.SysUserPowerMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.base.domain.bo.BaseBsZdBo;
import com.ruoyi.base.domain.vo.BaseBsZdVo;
import com.ruoyi.base.domain.BaseBsZd;
import com.ruoyi.base.mapper.BaseBsZdMapper;
import com.ruoyi.base.service.IBaseBsZdService;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 站点Service业务层处理
 *
 * @author zxs
 * @date 2024-09-25
 */
@RequiredArgsConstructor
@Service
public class BaseBsZdServiceImpl implements IBaseBsZdService {

    private final BaseBsZdMapper baseMapper;
    private final BaseBsBdMapper bdMapper;
    private final SysUserPowerMapper powerMapper;
    private final IBaseBsBdService bdService;
    //开工预付款
    private final CmBsStartAdvanceMapper advanceMapper;
    //合同信息；
    private final CmBsContractInfoMapper contractInfoMapper;



    /**
     * 查询站点
     */
    @Override
    public BaseBsZdVo queryById(Long id){
        BaseBsZdVo vo = baseMapper.selectVoById(id);
        //所属标段；
        BaseBsBdVo bdVo = bdMapper.selectVoById(vo.getBdId());
        if (ObjectUtils.isEmpty(vo.getJiansrlActual())) {
            vo.setJiansrlActual(vo.getJiansrl());
        }
        if (ObjectUtils.isEmpty(vo.getZdContractAmountActual())) {
            vo.setZdContractAmountActual(vo.getZdContractAmount());
        }
        vo.setBdName(bdVo.getName());
        return vo;
    }

    /**
     * 查询站点列表
     */
    @Override
    public TableDataInfo<BaseBsZdVo> queryPageList(BaseBsZdBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BaseBsZd> lqw = buildQueryWrapper(bo);
        Page<BaseBsZdVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
//        List<BaseBsZdVo> records = result.getRecords();
//        if(CollUtil.isNotEmpty(records)){
//            //过滤关联的站点
//            Long userId = LoginHelper.getUserId();
//            List<SysUserPower> powers = powerMapper.selectList(new LambdaQueryWrapper<SysUserPower>().eq(SysUserPower::getUserId, userId));
//            Set<Long> zdIds = powers.stream().map(SysUserPower::getPowerId).collect(Collectors.toSet());
//            List<BaseBsZdVo> collect = new ArrayList<>();
//            if(CollUtil.isNotEmpty(zdIds)){
//                collect = records.stream().filter(e -> zdIds.contains(e.getId())).collect(Collectors.toList());
//            }
//            result.setRecords(collect);
//        }
        // 处理实际建设容量和实际合同额,如果为空,则默认赋值为建设容量和合同额
        //赋值最新所属标段名称；
        List<BaseBsZdVo> records = result.getRecords();
        if(CollUtil.isNotEmpty(records)){
            BaseBsZdVo zdVo = records.get(0);
            BaseBsBdVo bdVo = bdMapper.selectVoById(zdVo.getBdId());
            records.forEach(item -> {
                item.setBdName(bdVo.getName());
                if (ObjectUtils.isEmpty(item.getJiansrlActual())) {
                    item.setJiansrlActual(item.getJiansrl());
                }
                if (ObjectUtils.isEmpty(item.getZdContractAmountActual())) {
                    item.setZdContractAmountActual(item.getZdContractAmount());
                }
            });
            result.setRecords(records);
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询站点列表
     */
    @Override
    public List<BaseBsZdVo> queryList(BaseBsZdBo bo) {
        LambdaQueryWrapper<BaseBsZd> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BaseBsZd> buildQueryWrapper(BaseBsZdBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BaseBsZd> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getBdId() != null, BaseBsZd::getBdId, bo.getBdId());
        lqw.eq(bo.getParentId() != null, BaseBsZd::getParentId, bo.getParentId());
        lqw.like(StringUtils.isNotBlank(bo.getName()), BaseBsZd::getName, bo.getName());
        lqw.eq(bo.getSort() != null, BaseBsZd::getSort, bo.getSort());
        lqw.eq(StringUtils.isNotBlank(bo.getJianscj()), BaseBsZd::getJianscj, bo.getJianscj());
        lqw.eq(bo.getJiansrl() != null, BaseBsZd::getJiansrl, bo.getJiansrl());
        lqw.eq(bo.getDanwzj() != null, BaseBsZd::getDanwzj, bo.getDanwzj());
        lqw.eq(StringUtils.isNotBlank(bo.getBeiazmc()), BaseBsZd::getBeiazmc, bo.getBeiazmc());
        lqw.like(StringUtils.isNotBlank(bo.getBdName()), BaseBsZd::getBdName, bo.getBdName());
        lqw.like(ObjectUtils.isNotEmpty(bo.getJiansrlActual()), BaseBsZd::getJiansrlActual, bo.getJiansrlActual());
        lqw.like(ObjectUtils.isNotEmpty(bo.getZdContractAmountActual()), BaseBsZd::getZdContractAmountActual, bo.getZdContractAmountActual());
        return lqw;
    }

    /**
     * 新增站点
     * 新增站点时，判断当前站点所属标段是否关联到用户，如果勾选了所属标段，把当前站点加到用户关联项目里；
     */
    @Override
    @DSTransactional
    public Boolean insertByBo(BaseBsZdBo bo) {
        BaseBsZd add = BeanUtil.toBean(bo, BaseBsZd.class);
        add.setJiansrlActual(add.getJiansrl());
        add.setZdContractAmountActual(add.getZdContractAmount());
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            List<SysUserPower> powers = powerMapper.selectList(new LambdaQueryWrapper<SysUserPower>().eq(SysUserPower::getPowerId, bo.getBdId()));
            if(CollUtil.isNotEmpty(powers)){
                powers.forEach(e->{
                    e.setPowerId(add.getId());
                    e.setId(null);
                });
            }
            powerMapper.insertBatch(powers);
        }
        return flag;
    }

    /**
     * 修改站点
     */
    @Override
    @DSTransactional
    public Boolean updateByBo(BaseBsZdBo bo) {
        BaseBsZd update = BeanUtil.toBean(bo, BaseBsZd.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     *
     * 2、校验站点总额合计是否超过合同额；
     */
    private void validEntityBeforeSave(BaseBsZd entity) {

//        //1、校验开工预付款状态；
//        List<CmBsStartAdvance> advances = advanceMapper.selectList(new LambdaQueryWrapper<CmBsStartAdvance>().eq(CmBsStartAdvance::getBdId, entity.getBdId()));
//        if (CollUtil.isNotEmpty(advances)) {
//            CmBsStartAdvance advance = advances.get(0);
//            if ("11".equals(advance.getReportFlag()) || "22".equals(advance.getReportFlag())) {
//                throw new ServiceException("已发起开工预付款审批流程，不允许新增或修改站点信息");
//            }
//        }
        //2、校验是否超过合同额；
        List<BaseBsZd> zdList = baseMapper.selectList(new LambdaQueryWrapper<BaseBsZd>().eq(BaseBsZd::getBdId, entity.getBdId()));
        BigDecimal zdhtze = entity.getZdContractAmountActual() == null ? BigDecimal.ZERO : entity.getZdContractAmountActual();
        if (CollUtil.isNotEmpty(zdList)) {
            if (entity.getId() != null) {
                zdList = zdList.stream().filter(e -> !e.getId().equals(entity.getId())).collect(Collectors.toList());
            }
            for (BaseBsZd zd : zdList) {
                zdhtze = BigDecimalUtil.add(zdhtze, zd.getZdContractAmountActual());
            }
        }
        //查询合同额；
        List<CmBsContractInfo> cmBsContractInfos = contractInfoMapper.selectList(new LambdaQueryWrapper<CmBsContractInfo>().eq(CmBsContractInfo::getBdId, entity.getBdId()));
        if (CollUtil.isNotEmpty(cmBsContractInfos)) {
            CmBsContractInfo contractInfo = cmBsContractInfos.get(0);
            if(contractInfo == null){
                throw new ServiceException("请先录入合同信息");
            }
            BigDecimal contractAmount = contractInfo.getChgContractAmount() == null ? contractInfo.getContractAmount() : contractInfo.getChgContractAmount();
            if(contractAmount == null||contractAmount.compareTo(BigDecimal.ZERO)<=0){
                throw new ServiceException("请先录入合同信息");
            }
            if (BigDecimalUtil.isGreaterThan(zdhtze, contractAmount)) {
                throw new ServiceException("站点实际总合同额超过变更后合同总额，不允许新增或修改站点信息");
            }
        }
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除站点
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
